﻿using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Microsoft.VisualBasic;

namespace Meotom.Upload.v2.Data.Utilities
{
    public class ImageUtil
    {
        public ImageUtil(Stream stream, int lx, int ly, string uploadType, string userName, string fileName, int quality)
        {
            Stream = stream;
            Lx = lx;
            Ly = ly;
            Quality = quality;
            UploadType = uploadType;
            UserName = userName;
            FileName = fileName;
        }

        public ImageUtil(string path, int lx, int ly, string uploadType, string userName, string fileName)
        {
            Path = path;
            Lx = lx;
            Ly = ly;
            UploadType = uploadType;
            UserName = userName;
            FileName = fileName;
        }

        public ImageUtil(string path, int lx, int ly, int x, int y, string uploadType, string userName, string fileName)
        {
            Path = path;
            Lx = lx;
            Ly = ly;
            X = x;
            Y = y;
            UploadType = uploadType;
            UserName = userName;
            FileName = fileName;
        }


        public int Quality { get; set; }
        public int X { get; set; }
        public int Y { get; set; }
        public string FileName { get; set; }
        public string UserName { get; set; }
        public string Copyright { get; set; }
        public string Path { get; set; }
        public int Lx { get; set; }
        public int Ly { get; set; }
        public string UploadType { get; set; }
        public Stream Stream { get; set; }

        public bool CropImage()
        {
            try
            {
                Image originalimg;

                if (string.IsNullOrEmpty(Path))
                {
                    originalimg = Image.FromStream(Stream);
                }
                else
                {
                    Path = Configs.UserFolder + Path.Replace("/Files/", "").Replace("/", "\\");
                    if (File.Exists(Path))
                    {
                        originalimg = Image.FromFile(Path);
                        //JustinSLR/avatar/JustinSLR_avatar__20100410002144IzYp.jpg
                    }
                    else
                    {
                        //originalimg = System.Drawing.Image.FromFile(Configs.UserFolder & "no_image_s.gif")
                        return false;
                    }
                }

                var thumb = new Bitmap(Lx, Ly);
                var grDest = Graphics.FromImage(thumb);
                dynamic sb = new SolidBrush(Color.White);

                grDest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height);
                grDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                grDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                grDest.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                //gr_dest.DrawImage(originalimg, X, Y, thumb.Width, thumb.Height)
                grDest.DrawImage(originalimg, new Rectangle(0, 0, thumb.Width, thumb.Height), X, Y,
                                  thumb.Width, thumb.Height, GraphicsUnit.Pixel);

                grDest.Save();

                switch (UploadType)
                {
                    case "Avatar":
                        {
                            string strFolderAvatar = Configs.UserFolder + UserName + "\\avatar\\";
                            if (!Directory.Exists(strFolderAvatar))
                            {
                                Directory.CreateDirectory(strFolderAvatar);
                            }
                            thumb.Save(strFolderAvatar + FileName, ImageFormat.Jpeg);
                        }
                        break;
                    case "CropImage":
                        break;
                }

                thumb.Dispose();
                originalimg.Dispose();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool OriImageFixSize()
        {
            try
            {
                Image originalimg;

                if (string.IsNullOrEmpty(Path))
                {
                    originalimg = Image.FromStream(Stream);
                }
                else
                {
                    if (File.Exists(Path))
                    {
                        Path = Configs.UserFolder + Path.Replace("/Files/", "").Replace("/", "\\");
                        originalimg = Image.FromFile(Path);
                    }
                    else
                    {
                        originalimg = Image.FromFile(Configs.UserFolder + "no_image_s.gif");
                    }
                }

                var bFlag = originalimg.Width <= Lx;

                if (bFlag)
                {
                    var strFolderAvatar = Configs.UserFolder + UserName + "\\avatar\\";
                    if (!Directory.Exists(strFolderAvatar))
                    {
                        Directory.CreateDirectory(strFolderAvatar);
                    }
                    originalimg.Save(strFolderAvatar + FileName, ImageFormat.Jpeg);

                    originalimg.Dispose();
                }
                return bFlag;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool ResizeImage()
        {
            try
            {
                int i;
                int newWidth;
                int newHeight;
                Image originalimg;

                if (string.IsNullOrEmpty(Path))
                {
                    originalimg = Image.FromStream(Stream);
                }
                else
                {
                    if (File.Exists(Path))
                    {
                        Path = Configs.UserFolder + Path.Replace("/Files/", "").Replace("/", "\\");
                        originalimg = Image.FromFile(Path);
                    }
                    else
                    {
                        originalimg = Image.FromFile(Configs.UserFolder + "no_image_s.gif");
                    }
                }

                if (originalimg.Width < Lx | originalimg.Height < Ly)
                {
                    newHeight = originalimg.Height - ((originalimg.Height*15)/100);
                    newWidth = originalimg.Width - ((originalimg.Width*15)/100);
                    i = 1;
                }
                else
                {
                    newHeight = Ly;
                    newWidth = Lx;
                    i = 0;
                }

                var thumb = new Bitmap(newWidth, newHeight);
                var grDest = Graphics.FromImage(thumb);
                dynamic sb = new SolidBrush(Color.White);
                grDest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height);
                grDest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height);
                grDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                grDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                if (!string.IsNullOrEmpty(Copyright))
                {
                    grDest.DrawString(Copyright, new Font("Arial", 10), new SolidBrush(Color.Blue),
// ReSharper disable PossibleLossOfFraction
                                       (thumb.Width*60)/100, (thumb.Height*1)/100);
// ReSharper restore PossibleLossOfFraction
                }

                if (i == 1)
                {
                    grDest.Save();
                    if (UploadType == "Avatar")
                    {
                        string strFolderAvatar = Configs.UserFolder + UserName + "\\avatar\\";
                        if (!Directory.Exists(strFolderAvatar))
                        {
                            Directory.CreateDirectory(strFolderAvatar);
                        }
                        thumb.Save(strFolderAvatar + FileName, ImageFormat.Jpeg);
                    }
                }
                else
                {
                    grDest.Save();
                    if (UploadType == "Avatar")
                    {
                        var strFolderAvatar = Configs.UserFolder + UserName + "\\avatar\\";
                        if (!Directory.Exists(strFolderAvatar))
                        {
                            Directory.CreateDirectory(strFolderAvatar);
                        }
                        thumb.Save(strFolderAvatar + FileName, ImageFormat.Jpeg);
                    }
                }

                thumb.Dispose();
                originalimg.Dispose();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string PublicUpload(int lx, int ly, string fileName, int quality, string copyRight)
        {
            Lx = lx;
            Ly = ly;
            Quality = quality;
            FileName = lx + "x" + ly + "__" + fileName;
            return PublicUpload(copyRight);
        }

        public string PublicUpload(string copyright)
        {
            try
            {
                string strMsg;
                Copyright = copyright;
                int i;
                int newWidth;
                int newHeight;
                Image originalimg;
                var strPhyPath = ConfigurationManager.AppSettings["UserFolder"];

                if (string.IsNullOrEmpty(Path))
                {
                    originalimg = Image.FromStream(Stream);
                }
                else
                {
                    if (File.Exists(Path))
                    {
                        Path = Configs.UserFolder + Path.Replace("/Files/", "").Replace("/", "\\");
                        originalimg = Image.FromFile(Path);
                    }
                    else
                    {
                        originalimg = Image.FromFile(Configs.UserFolder + "no_image_s.gif");
                    }
                }

                if (originalimg.Width <= Lx)
                {
                    newWidth = originalimg.Width;
                    newHeight = originalimg.Height;
                    i = 1;
                }
                else
                {
                    var dAspect = (double)originalimg.Height / (double)originalimg.Width;
                    newWidth = Lx;
                    newHeight = Convert.ToInt32(Math.Round(Lx*dAspect));

                    i = 0;
                }

                var thumb = new Bitmap(newWidth, newHeight);
                var grDest = Graphics.FromImage(thumb);
                dynamic sb = new SolidBrush(Color.White);
                grDest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height);
                grDest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height);

                if (newWidth == 160 & newHeight > 120)
                {
                    strMsg = "Crop";
                }
                else
                {
                    strMsg = "OK";
                }

                //set quality for image
                grDest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                grDest.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                //new add
                grDest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                grDest.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                //end set

                //write copyright text on image
                if (!string.IsNullOrEmpty(copyright))
                {
                    if (newWidth > 230 & newHeight > 200)
                    {
                        grDest.DrawString(copyright, new Font("Verdana", 10), new SolidBrush(Color.Blue),
                                           newWidth - 235, newHeight - 17);
                    }
                }

                var codecEncoder = GetEncoder("image/jpeg");
                var encodeParams = new EncoderParameters(1);
                var qualityParam = new EncoderParameter(Encoder.Quality, Quality);
                encodeParams.Param[0] = qualityParam;

                var strFolderUpload = strPhyPath + Common.Instance.SplitString(UserName)[3] + "\\";
                if (!Directory.Exists(strFolderUpload))
                {
                    Directory.CreateDirectory(strFolderUpload);
                }

                if (i == 1)
                {
                    grDest.Save();
                    if (UploadType == "UploadService")
                    {
                        thumb.Save(strFolderUpload + FileName, codecEncoder, encodeParams);
                    }
                }
                else
                {
                    grDest.Save();
                    if (UploadType == "UploadService")
                    {
                        thumb.Save(strFolderUpload + FileName, codecEncoder, encodeParams);
                    }
                }

                thumb.Dispose();
                originalimg.Dispose();

                return strMsg;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public ImageCodecInfo GetEncoder(string mimeType)
        {
            return ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.MimeType == mimeType);
        }
    }
}